/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: FeverClinicController
 * Author:   Administrator
 * Date:     2020/2/24 17:51
 * Description: 发热服务
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.authine.cloudpivot.web.api.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.web.Utils.FeverHnTelcom;
import com.authine.cloudpivot.web.Utils.HttpClientUtils;
import com.authine.cloudpivot.web.Utils.RSAUtils;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.service.FeverService;
import com.authine.cloudpivot.web.api.service.RedisService;
import com.authine.cloudpivot.web.api.vo.FeverClinicSurveyInfoVo;
import com.authine.cloudpivot.web.api.vo.FeverPatientsInfoVo;
import com.authine.cloudpivot.web.api.vo.HainanAreaDimensionVo;
import com.authine.cloudpivot.web.enums.HkAppFuncEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 〈一句话功能简述〉<br> 
 * 〈发热服务〉
 *
 * @author Administrator
 * @create 2020/2/24
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/hkgy")
@Slf4j
public class FeverClinicController extends BaseController {

    @Autowired
    FeverService feverService;
    @Autowired
    RedisService redisService;
    // 2020-02-28 00:00:00
    private static final  long pushStartDate = 1582819200000L;

    private static final  String ls = "秀英区,龙华区,琼山区,美兰区";

    @RequestMapping("/pushFeverPatientsInfo")
    public void pushFeverPatientsInfo(String objectId){

        if (StringUtils.isEmpty(objectId)) {
            log.info("push发热用户信息 objectId 为null");
        }

        try {

            BizObjectCreatedModel bizObject = super.getBizObjectFacade().getBizObject(HkAppFuncEnum.FRMZDJ.code, objectId);

            if (log.isDebugEnabled()) {
                log.debug("push发热用户信息 创建时间 CreatedTime={}",bizObject.getCreatedTime());
                log.debug("push发热用户信息 存量数据时间 pushStartDate={}", new Date(pushStartDate));
            }


            if (bizObject.getCreatedTime() == null || bizObject.getCreatedTime().getTime()<pushStartDate){
                log.info("push发热用户信息2020/02/28 之前的存量数据,不推送");
                return;
            }

            if (!"是".equals(bizObject.getData().get("isValid"))){
                log.info("push发热用户信息 不是有效数据,不用推送");
                return;
            }

            FeverPatientsInfoVo fpi = getMapToFpiv(bizObject);

            if (fpi == null ){
                log.info("push发热用户信息 fpi 为null");
                return;
            }


            List<FeverPatientsInfoVo> list = new ArrayList<>();
            list.add(fpi);
            //{"statusCode":"0","status":"SUCCESS","result":"接收成功"}
            String s = HttpClientUtils.doPost(FeverHnTelcom.ferverUrl, RSAUtils.getSignJsonData(list));
            log.info("push发热用户信息 返回结果:{}", s);

            JSONObject result = (JSONObject) JSON.parse(s.trim());
            String statusCode = (String) result.get("statusCode");
            if ("0".equals(statusCode)){
                log.info("push发热用户信息成功 objectId ={}",objectId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("系统异常:{}",e.getMessage());
            log.info("push发热用户信息 系统异常 objectId = {}", objectId);
        }

    }


    private FeverPatientsInfoVo getMapToFpiv(BizObjectCreatedModel bizObject){
        Map<String,Object> data = bizObject.getData();
        FeverPatientsInfoVo fpi = new FeverPatientsInfoVo();
        if (data == null || data.isEmpty()) {
            return null;
        }
        String mobile =  (String) data.get("mobile");
        String personName = (String) data.get("personName");

        if (StringUtils.isEmpty(mobile) ){
            return  null;
        }
        log.info("push发热用户信息 数据整理");

        fpi.setFeverClinicSurveyPersonId(bizObject.getId());
        fpi.setPhoneNumber(mobile);
        fpi.setName(personName);
        fpi.setParentsName((String) data.get("parentName"));
        fpi.setAge(Integer.valueOf((String) data.get("age")) );
        String ageMonthNum = (String) data.get("ageMonthNum");
        fpi.setAgeMonthNum(StringUtils.isEmpty(ageMonthNum)?0:Integer.valueOf(ageMonthNum));

        String idCard = (String) data.get("idCard");

        if (StringUtils.isNotEmpty(idCard) && idCard.length()!=18){
            idCard = null;
        }

        fpi.setIdNumber(idCard);
        fpi.setGender("男".equals(data.get("gender"))?0:1);

        fpi.setFamilyBooleanGhubei("湖北省".equals(data.get("problem1"))?"1":"0");

        String isJzhk = (String) data.get("isJzhk");
        log.info("push发热用户信息 地址判断");
        String cityName, areaName, townshipName,addrDetail;
        if ("是".equals(isJzhk)) {
            cityName = (String) data.get("area");
            areaName = (String) data.get("street");
            townshipName = (String) data.get("villageHotel");
            addrDetail = (String) data.get("houseNumber");
        }else{
            cityName = (String) data.get("fromCity");
            areaName = (String) data.get("fromStreet");
            townshipName = (String) data.get("fromVillageHotel");
            addrDetail = (String) data.get("detailAdds");
        }

        HainanAreaDimensionVo areaDimension = getAreaDimension(cityName, areaName, townshipName);

        fpi.setCityInfoId(areaDimension.getCityId());
        fpi.setCityName(areaDimension.getCityName());
        fpi.setTownshipInfoId(areaDimension.getTownshipId());
        fpi.setTownshipName(areaDimension.getAreaName());
        fpi.setVillageCommunityInfoId(areaDimension.getTownshipId());
        fpi.setVillageCommunityName(areaDimension.getTownshipName());

        fpi.setAddressDetail(addrDetail);


        String hospitalName = (String) data.get("hospitalName");

        Map<String, String> hospitalInfo = feverService.getHospitalInfo(hospitalName);

        fpi.setHospitalInfoId(hospitalInfo.get("dxCode"));
        fpi.setHospitalName(hospitalInfo.get("hospitalName"));


        //============= 就诊信息 ================

        // 就诊信息
        FeverClinicSurveyInfoVo fcsiv = new FeverClinicSurveyInfoVo();

        fcsiv.setHsPersonStateId(bizObject.getId());
        fcsiv.setFeverClinicSurveyPersonId(bizObject.getId());
        fcsiv.setHospitalInfoId(hospitalInfo.get("dxCode"));
        fcsiv.setConsultationDate((Date) data.get("zdsj"));
        fcsiv.setMorbidityDate(bizObject.getCreatedTime());


        fcsiv.setWhereaboutsId("5");
        fcsiv.setWhereaboutsName("其他");

        String temperature = (String) data.get("temperature");

        if (StringUtils.isNotEmpty(temperature)){

            if("40以上".equals(temperature)){
                fcsiv.setTemperature(40d);
            }else if ("37以下".equals(temperature)) {
                fcsiv.setTemperature(37d);
            }else {
                fcsiv.setTemperature(Double.valueOf(temperature));
            }
        }else{
            fcsiv.setTemperature(37d);
        }


        fcsiv.setBooleanHealthy("是".equals(data.get("yszlm"))?"1":"0");
        fcsiv.setRegistrationStatusTime(fcsiv.getConsultationDate());
        fcsiv.setRemark((String) data.get("jcjg"));

        List<FeverClinicSurveyInfoVo> fcsivList = new ArrayList<>();
        String symptoms = (String) data.get("symptoms");

        if (fcsiv.getTemperature() != null && fcsiv.getTemperature()>=37.3){
            fcsiv.setBooleanHaveFever(1);
        }else{
            fcsiv.setBooleanHaveFever(0);
        }

        if (StringUtils.isNotEmpty(symptoms) && symptoms.indexOf("咳嗽")!= -1){
            fcsiv.setBooleanCoughChestTightness(1);
        }else {
            fcsiv.setBooleanCoughChestTightness(0);
        }


        fcsiv.setZzArr(FeverHnTelcom.getZzArrVoList(symptoms));
        fcsivList.add(fcsiv);
        fpi.setJzxxJson(fcsivList);

        return fpi;
    }


    public HainanAreaDimensionVo getAreaDimension(String cityName, String areaName, String townshipName){
        List<HainanAreaDimensionVo>  list = new ArrayList<>();
        if (StringUtils.isNotEmpty(townshipName)) {
            list =  feverService.getHainanAreaDimensionByTownshipName(townshipName);
        }
        if (listIsEmpty(list) && StringUtils.isNotEmpty(areaName)) {
            list =  feverService.getHainanAreaDimensionByAreaName(areaName);
        }
        if (listIsEmpty(list) && StringUtils.isNotEmpty(cityName)) {
            list =  feverService.getHainanAreaDimensionByAreaName(cityName);
        }

        if (listIsEmpty(list)) {
            return new HainanAreaDimensionVo();
        }
        HainanAreaDimensionVo had  = list.get(0);
        if (ls.indexOf(had.getCityName())!=-1){
            had.setCityName("海口市".concat(had.getCityName()));
        }

        return had;
    }

    public boolean listIsEmpty(List list){

        if (list == null || list.isEmpty()) {
            return true;
        }

        return false;
    }


    @RequestMapping("/feverControl")
    public void feverControl(String objectId){
        log.info("发热管控信息 objectId = {}",objectId);
        if (StringUtils.isEmpty(objectId)) {
            return;
        }

        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();

        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(HkAppFuncEnum.FRMZDJ.code, objectId);
        Map<String, Object> data = bizObject.getData();
        if (!"是".equals(data.get("isValid"))){
            log.info("发热用户信息 不是有效数据,不用加入管控");
            return;
        }

        int feverInfoCount = feverService.getFeverInfoCount(bizObject.getId());

        if (feverInfoCount > 0){
            log.info("发热用户信息已存在");
            return;
        }


        Map<String,Object>  bizData =  new HashMap<>();
        getCopyBizData(data, bizData);

        cleanSysField(bizData);
        bizData.put("feverId", bizObject.getId());
        bizData.put("sequenceStatus", "COMPLETED");
        log.info("发热管控信息 data = {}",JSON.toJSONString(data));


        log.info("发热管控信息 创建bizObject");
        BizObjectCreatedModel controlFever = new BizObjectCreatedModel("controlFever", bizData, false);

        log.info("发热管控信息 开始保存, biz={}",JSON.toJSONString(controlFever));
        bizObjectFacade.saveBizObject(super.getUserId(), controlFever, true);

        log.info("发热管控信息 加入成功");


    }


    @RequestMapping("/pharmacyControl")
    public void pharmacyControl(String objectId){
        log.info("药店管控信息 objectId = {}",objectId);
        if (StringUtils.isEmpty(objectId)) {
            return;
        }

        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();

        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(HkAppFuncEnum.LSYDGM.code, objectId);
        Map<String, Object> data = bizObject.getData();

        int pharmacyBuyCount = feverService.getPharmacyBuyInfoCount(bizObject.getId());

        if (pharmacyBuyCount > 0){
            log.info("药店管控信息已存在,bizObject.getId()={},pharmacyBuyCount={}",bizObject.getId(),pharmacyBuyCount);
            return;
        }

        Map<String,Object>  bizData =  new HashMap<>();
        getCopyBizData(data, bizData);

        cleanSysField(bizData);
        bizData.put("pharmacyBuyId", bizObject.getId());
        bizData.remove("drugs");
        bizData.put("sequenceStatus", "COMPLETED");
        bizData.put("drugsBuyDate", bizObject.getCreatedTime());
        bizData.put("processingState", "待管控");
        log.info("药店管控信息 drugsBuyDate={}",bizObject.getCreatedTime());


        Object drugs = data.get("drugs");

        log.info("药店管控信息 子表={}",drugs);

        List<Map<String,Object>> drugsBiz = (ArrayList<Map<String,Object>>) data.get("drugs");
        List<Map<String,Object>> drugsControlArr = null;
        if (drugsBiz != null && drugsBiz.size() >0){
            drugsControlArr = new ArrayList<>();

            Map<String, Object> drugsBizData = null;

            for (int i = 0; i < drugsBiz.size(); i++) {

                log.info("药店管控信息 子表={}",drugsBiz.get(i));

                drugsBizData = new HashMap<>();
                getCopyBizData(drugsBiz.get(i), drugsBizData);
                cleanSysField(drugsBizData);
                drugsControlArr.add(drugsBizData);

            }
            bizData.put("controlDrugs",drugsControlArr);
        }

        BizObjectCreatedModel biz = new BizObjectCreatedModel("controlPharmacy",bizData,false);
        log.info("药店管控信息 开始保存biz={}",JSON.toJSONString(biz));
        bizObjectFacade.saveBizObject(FeverHnTelcom.adminId, biz, true);

        log.info("药店管控信息 加入成功");


    }


    @RequestMapping("/pharmacyScheduleds")
    public String pharmacyScheduleds(String startDate,String endDate){

        try {
            log.info("手动调用药品管控定时任务startDate={},endDate={}",startDate,endDate);
            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
                return  "null";
            }

            pharmacyScheduled(startDate, endDate);

        } catch (Exception e) {
            return  "fail";
        }

        return  "success";
    }


    /**
     *  药品管控定时任务每天 00:10:00,17:10:00 执行 [17:00-24:00), [0:00-17:00)
     */
    @Scheduled(cron = "0 10 0,17 * * ?")
    public  void controlPharmacyScheduled(){
        log.info("药品管控定时任务 开始");
        try {
            Date now = new Date();

            int h = Integer.valueOf(DateFormatUtils.format(now, "HH"));
            String startDate,endDate,nowForamtY = DateFormatUtils.format(now, "yyyy-MM-dd");
            // 执行前一天 17 点到 00 点的
            if (h == 0) {
                now = DateUtils.addDays(now, -1);
                startDate = DateFormatUtils.format(now, "yyyy-MM-dd").concat(" 17:00:00");
                endDate  = nowForamtY.concat(" 00:00:00");
            }else{
                // 执行今天  0点到17 点的
                startDate = nowForamtY.concat(" 00:00:00");
                endDate  = nowForamtY.concat(" 17:00:00");
            }


            pharmacyScheduled(startDate, endDate);

        } catch (Exception e) {
            log.info("药品管控定时任务 系统异常");
        }

        log.info("药品管控定时任务 结束");

    }

    private void pharmacyScheduled(String startDate, String endDate) {
        List<String> list = feverService.getPharmacySyncList(startDate,endDate);

        if (list == null || list.isEmpty()) {
            log.info("药品管控定时任务 list is null or Empty");
        }else{
            log.info("药品管控定时任务 list.size = {}", list.size());
            list.parallelStream().forEach(ac -> {

                try {
                    this.pharmacyControl(ac);
                } catch (Exception e) {
                    log.info("药店管控同步信息 异常 objectId = {}",ac);
                }

            });
        }
    }

    private void getCopyBizData(Map<String, Object> data, Map<String, Object> bizData) {
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() != null && !"".equals(entry.getValue())) {
                bizData.put(entry.getKey(), entry.getValue());
            }
        }
    }

    private void cleanSysField(Map<String, Object> data) {
        String[] field = FeverHnTelcom.SysFeild;
        for (int i = 0; i < field.length; i++) {
            data.remove(field[i]);
        }
    }

}